package com.stylefeng.guns.modular.vpn.mquartz;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;

/**
 * @Description 解决@Autowired空指针Null问题，即依赖注入的属性为null
 * @Author Mr.God
 * @Date 2020-03-15 16:26
 **/
@Component("springQuartzJobFactory")
public class SpringQuartzJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    @Autowired
    private AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object object = super.createJobInstance(bundle);
        beanFactory.autowireBean(object);
        return object;
    }
}

/*
主要思路是通过新建一个AutowiringSpringBeanJobFactory 实现 quartz 的SpringBeanJobFactory（job生产工厂类）
通过实现ApplicationContextAware接口 set ApplicationContextAware(上下文)到该新建job工厂类。
然后通过super.createJobInstance(bundle) 创建 job，　beanFactory来autowired job实例
*/

